/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.fatecpg.gradeHoraria;

import java.io.IOException;
import java.util.Vector;
import javax.microedition.io.Connection;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.io.StreamConnection;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

/**
 * @author Thyago
 */
public class GradeHorariaMIDlet extends MIDlet implements CommandListener {

    private boolean midletPaused = false;
//<editor-fold defaultstate="collapsed" desc=" Generated Fields ">//GEN-BEGIN:|fields|0|
    private Command sairCommand;
    private Command conectarCommand;
    private Command backCommand;
    private Form loginForm;
    private ChoiceGroup cursoChoiceGroup;
    private Spacer spacer;
    private ChoiceGroup periodoChoiceGroup;
    private ChoiceGroup diaChoiceGroup;
    private Spacer spacer1;
    private ImageItem imageItem;
    private List horariosList;
    private Image logoImage;
//</editor-fold>//GEN-END:|fields|0|

    /**
     * The GradeHorariaMIDlet constructor.
     */
    public GradeHorariaMIDlet() {
    }

//<editor-fold defaultstate="collapsed" desc=" Generated Methods ">//GEN-BEGIN:|methods|0|
//</editor-fold>//GEN-END:|methods|0|
//<editor-fold defaultstate="collapsed" desc=" Generated Method: initialize ">//GEN-BEGIN:|0-initialize|0|0-preInitialize
    /**
     * Initializes the application. It is called only once when the MIDlet is
     * started. The method is called before the
     * <code>startMIDlet</code> method.
     */
    private void initialize() {//GEN-END:|0-initialize|0|0-preInitialize
        // write pre-initialize user code here
//GEN-LINE:|0-initialize|1|0-postInitialize
        // write post-initialize user code here
    }//GEN-BEGIN:|0-initialize|2|
//</editor-fold>//GEN-END:|0-initialize|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Method: startMIDlet ">//GEN-BEGIN:|3-startMIDlet|0|3-preAction
    /**
     * Performs an action assigned to the Mobile Device - MIDlet Started point.
     */
    public void startMIDlet() {//GEN-END:|3-startMIDlet|0|3-preAction
        // write pre-action user code here
        switchDisplayable(null, getLoginForm());//GEN-LINE:|3-startMIDlet|1|3-postAction
        // write post-action user code here
    }//GEN-BEGIN:|3-startMIDlet|2|
//</editor-fold>//GEN-END:|3-startMIDlet|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Method: resumeMIDlet ">//GEN-BEGIN:|4-resumeMIDlet|0|4-preAction
    /**
     * Performs an action assigned to the Mobile Device - MIDlet Resumed point.
     */
    public void resumeMIDlet() {//GEN-END:|4-resumeMIDlet|0|4-preAction
        // write pre-action user code here
//GEN-LINE:|4-resumeMIDlet|1|4-postAction
        // write post-action user code here
    }//GEN-BEGIN:|4-resumeMIDlet|2|
//</editor-fold>//GEN-END:|4-resumeMIDlet|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Method: switchDisplayable ">//GEN-BEGIN:|5-switchDisplayable|0|5-preSwitch
    /**
     * Switches a current displayable in a display. The
     * <code>display</code> instance is taken from
     * <code>getDisplay</code> method. This method is used by all actions in the
     * design for switching displayable.
     *
     * @param alert the Alert which is temporarily set to the display; if
     * <code>null</code>, then
     * <code>nextDisplayable</code> is set immediately
     * @param nextDisplayable the Displayable to be set
     */
    public void switchDisplayable(Alert alert, Displayable nextDisplayable) {//GEN-END:|5-switchDisplayable|0|5-preSwitch
        // write pre-switch user code here
        Display display = getDisplay();//GEN-BEGIN:|5-switchDisplayable|1|5-postSwitch
        if (alert == null) {
            display.setCurrent(nextDisplayable);
        } else {
            display.setCurrent(alert, nextDisplayable);
        }//GEN-END:|5-switchDisplayable|1|5-postSwitch
        // write post-switch user code here
    }//GEN-BEGIN:|5-switchDisplayable|2|
//</editor-fold>//GEN-END:|5-switchDisplayable|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Method: commandAction for Displayables ">//GEN-BEGIN:|7-commandAction|0|7-preCommandAction
    /**
     * Called by a system to indicated that a command has been invoked on a
     * particular displayable.
     *
     * @param command the Command that was invoked
     * @param displayable the Displayable where the command was invoked
     */
    public void commandAction(Command command, Displayable displayable) {//GEN-END:|7-commandAction|0|7-preCommandAction
        // write pre-action user code here
        if (displayable == horariosList) {//GEN-BEGIN:|7-commandAction|1|64-preAction
            if (command == List.SELECT_COMMAND) {//GEN-END:|7-commandAction|1|64-preAction
                // write pre-action user code here
                horariosListAction();//GEN-LINE:|7-commandAction|2|64-postAction
                // write post-action user code here
            } else if (command == backCommand) {//GEN-LINE:|7-commandAction|3|67-preAction
                // write pre-action user code here
                switchDisplayable(null, getLoginForm());//GEN-LINE:|7-commandAction|4|67-postAction
                // write post-action user code here
            }//GEN-BEGIN:|7-commandAction|5|23-preAction
        } else if (displayable == loginForm) {
            if (command == conectarCommand) {//GEN-END:|7-commandAction|5|23-preAction
                //Link utilizado para consumir feed RSS da lista de Horários de Aula dos Cursos
                String url = "http://www.fatecpg.com.br/fatec/_layouts/listfeed.aspx?List="
                        + "{8E031B92-F1D8-4746-BBAD-EE3359E93439}"; //URL para consumo RSS da lista de falta de professores

                try {
                    //Limpa a lista, caso tenha algo anteriormente
                    getHorariosList().deleteAll();
                    //Estabelece a conexão com o site
                    StreamConnection connection = (StreamConnection) Connector.open(url, Connector.READ_WRITE);
                    //Faz o parser do XML obtido de resposta
                    SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
                    //Handler responsável pro trabalhar as informações do XML
                    saxParser.parse(connection.openInputStream(), new DefaultHandler() {

                        private String currentName = "";
                        //Recupera a tag atual do XML

                        public void startElement(String uri, String lName, String name, Attributes att) throws SAXException {
                            currentName = name;
                        }
                        //Recupera a String e faz os filtros de acordo com o que foi selecionado pelo usuário

                        public void characters(char[] ch, int start, int length) throws SAXException {
                            String chars = new String(ch, start, length).trim();
                            String textoFormatado = tratarTagsHtml(chars);
                            if (chars.length() > 0) {
                                if (currentName.equals("description")) {
                                    Vector horarios = filtrarGrade(textoFormatado);
                                    for (int i = 0; i < horarios.size(); i++) {
                                        getHorariosList().append((String) horarios.elementAt(i), null);
                                    }
                                }
                            }
                        }
                    });
                    // em casa de falha exibe a mensagem "Erro ao acessar base de dados."
                } catch (Exception error) {
                    Alert mensagem = new Alert("Erro ao acessar base de dados.");
                    mensagem.setString(error.getMessage());
                    mensagem.setTimeout(3000);
                    getDisplay().setCurrent(mensagem);
                }
                switchDisplayable(null, getHorariosList());//GEN-LINE:|7-commandAction|6|23-postAction

            } else if (command == sairCommand) {//GEN-LINE:|7-commandAction|7|19-preAction
                // write pre-action user code here
                exitMIDlet();//GEN-LINE:|7-commandAction|8|19-postAction
                // write post-action user code here
            }//GEN-BEGIN:|7-commandAction|9|7-postCommandAction
        }//GEN-END:|7-commandAction|9|7-postCommandAction
        // write post-action user code here
    }//GEN-BEGIN:|7-commandAction|10|
//</editor-fold>//GEN-END:|7-commandAction|10|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: sairCommand ">//GEN-BEGIN:|18-getter|0|18-preInit
    /**
     * Returns an initialized instance of sairCommand component.
     *
     * @return the initialized component instance
     */
    public Command getSairCommand() {
        if (sairCommand == null) {//GEN-END:|18-getter|0|18-preInit
            // write pre-init user code here
            sairCommand = new Command("Sair", Command.EXIT, 0);//GEN-LINE:|18-getter|1|18-postInit
            // write post-init user code here
        }//GEN-BEGIN:|18-getter|2|
        return sairCommand;
    }
//</editor-fold>//GEN-END:|18-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: loginForm ">//GEN-BEGIN:|14-getter|0|14-preInit
    /**
     * Returns an initialized instance of loginForm component.
     *
     * @return the initialized component instance
     */
    public Form getLoginForm() {
        if (loginForm == null) {//GEN-END:|14-getter|0|14-preInit
            // write pre-init user code here
            loginForm = new Form("Grade Hor\u00E1ria - FATEC PG", new Item[]{getImageItem(), getCursoChoiceGroup(), getSpacer(), getPeriodoChoiceGroup(), getSpacer1(), getDiaChoiceGroup()});//GEN-BEGIN:|14-getter|1|14-postInit
            loginForm.addCommand(getSairCommand());
            loginForm.addCommand(getConectarCommand());
            loginForm.setCommandListener(this);//GEN-END:|14-getter|1|14-postInit
            // write post-init user code here
        }//GEN-BEGIN:|14-getter|2|
        return loginForm;
    }
//</editor-fold>//GEN-END:|14-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: conectarCommand ">//GEN-BEGIN:|22-getter|0|22-preInit
    /**
     * Returns an initialized instance of conectarCommand component.
     *
     * @return the initialized component instance
     */
    public Command getConectarCommand() {
        if (conectarCommand == null) {//GEN-END:|22-getter|0|22-preInit
            // write pre-init user code here
            conectarCommand = new Command("Conectar", Command.ITEM, 0);//GEN-LINE:|22-getter|1|22-postInit
            // write post-init user code here
        }//GEN-BEGIN:|22-getter|2|
        return conectarCommand;
    }
//</editor-fold>//GEN-END:|22-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: cursoChoiceGroup ">//GEN-BEGIN:|40-getter|0|40-preInit
    /**
     * Returns an initialized instance of cursoChoiceGroup component.
     *
     * @return the initialized component instance
     */
    public ChoiceGroup getCursoChoiceGroup() {
        if (cursoChoiceGroup == null) {//GEN-END:|40-getter|0|40-preInit
            // write pre-init user code here
            cursoChoiceGroup = new ChoiceGroup("Curso:", Choice.EXCLUSIVE);//GEN-BEGIN:|40-getter|1|40-postInit
            cursoChoiceGroup.append("An\u00E1lise e Desenv. de Sistemas", null);
            cursoChoiceGroup.append("Com\u00E9rcio Exterior", null);
            cursoChoiceGroup.append("Com\u00E9rcio Exterior 2", null);
            cursoChoiceGroup.append("Processos Qu\u00EDmicos", null);
            cursoChoiceGroup.append("Gest\u00E3o Empresarial", null);
            cursoChoiceGroup.append("Inform\u00E1tica para Gest\u00E3o de Neg.", null);
            cursoChoiceGroup.setSelectedFlags(new boolean[]{false, false, false, false, false, false});//GEN-END:|40-getter|1|40-postInit
            // write post-init user code here
        }//GEN-BEGIN:|40-getter|2|
        return cursoChoiceGroup;
    }
//</editor-fold>//GEN-END:|40-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: spacer ">//GEN-BEGIN:|46-getter|0|46-preInit
    /**
     * Returns an initialized instance of spacer component.
     *
     * @return the initialized component instance
     */
    public Spacer getSpacer() {
        if (spacer == null) {//GEN-END:|46-getter|0|46-preInit
            // write pre-init user code here
            spacer = new Spacer(16, 1);//GEN-LINE:|46-getter|1|46-postInit
            // write post-init user code here
        }//GEN-BEGIN:|46-getter|2|
        return spacer;
    }
//</editor-fold>//GEN-END:|46-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: periodoChoiceGroup ">//GEN-BEGIN:|47-getter|0|47-preInit
    /**
     * Returns an initialized instance of periodoChoiceGroup component.
     *
     * @return the initialized component instance
     */
    public ChoiceGroup getPeriodoChoiceGroup() {
        if (periodoChoiceGroup == null) {//GEN-END:|47-getter|0|47-preInit
            // write pre-init user code here
            periodoChoiceGroup = new ChoiceGroup("Per\u00EDodo:", Choice.EXCLUSIVE);//GEN-BEGIN:|47-getter|1|47-postInit
            periodoChoiceGroup.append("Vespertino", null);
            periodoChoiceGroup.append("Noturno", null);
            periodoChoiceGroup.setSelectedFlags(new boolean[]{false, false});//GEN-END:|47-getter|1|47-postInit
            // write post-init user code here
        }//GEN-BEGIN:|47-getter|2|
        return periodoChoiceGroup;
    }
//</editor-fold>//GEN-END:|47-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: spacer1 ">//GEN-BEGIN:|50-getter|0|50-preInit
    /**
     * Returns an initialized instance of spacer1 component.
     *
     * @return the initialized component instance
     */
    public Spacer getSpacer1() {
        if (spacer1 == null) {//GEN-END:|50-getter|0|50-preInit
            // write pre-init user code here
            spacer1 = new Spacer(16, 1);//GEN-LINE:|50-getter|1|50-postInit
            // write post-init user code here
        }//GEN-BEGIN:|50-getter|2|
        return spacer1;
    }
//</editor-fold>//GEN-END:|50-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: diaChoiceGroup ">//GEN-BEGIN:|51-getter|0|51-preInit
    /**
     * Returns an initialized instance of diaChoiceGroup component.
     *
     * @return the initialized component instance
     */
    public ChoiceGroup getDiaChoiceGroup() {
        if (diaChoiceGroup == null) {//GEN-END:|51-getter|0|51-preInit
            // write pre-init user code here
            diaChoiceGroup = new ChoiceGroup("Dia da Semana:", Choice.EXCLUSIVE);//GEN-BEGIN:|51-getter|1|51-postInit
            diaChoiceGroup.append("Segunda-Feira", null);
            diaChoiceGroup.append("Ter\u00E7a-Feira", null);
            diaChoiceGroup.append("Quarta-Feira", null);
            diaChoiceGroup.append("Quinta-Feira", null);
            diaChoiceGroup.append("Sexta-Feira", null);
            diaChoiceGroup.append("S\u00E1bado", null);
            diaChoiceGroup.setSelectedFlags(new boolean[]{false, false, false, false, false, false});//GEN-END:|51-getter|1|51-postInit
            // write post-init user code here
        }//GEN-BEGIN:|51-getter|2|
        return diaChoiceGroup;
    }
//</editor-fold>//GEN-END:|51-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: backCommand ">//GEN-BEGIN:|66-getter|0|66-preInit
    /**
     * Returns an initialized instance of backCommand component.
     *
     * @return the initialized component instance
     */
    public Command getBackCommand() {
        if (backCommand == null) {//GEN-END:|66-getter|0|66-preInit
            // write pre-init user code here
            backCommand = new Command("Voltar", Command.BACK, 0);//GEN-LINE:|66-getter|1|66-postInit
            // write post-init user code here
        }//GEN-BEGIN:|66-getter|2|
        return backCommand;
    }
//</editor-fold>//GEN-END:|66-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: horariosList ">//GEN-BEGIN:|63-getter|0|63-preInit
    /**
     * Returns an initialized instance of horariosList component.
     *
     * @return the initialized component instance
     */
    public List getHorariosList() {
        if (horariosList == null) {//GEN-END:|63-getter|0|63-preInit
            // write pre-init user code here
            horariosList = new List("Hor\u00E1rios do Dia", Choice.IMPLICIT);//GEN-BEGIN:|63-getter|1|63-postInit
            horariosList.addCommand(getBackCommand());
            horariosList.setCommandListener(this);//GEN-END:|63-getter|1|63-postInit
            // write post-init user code here
        }//GEN-BEGIN:|63-getter|2|
        return horariosList;
    }
//</editor-fold>//GEN-END:|63-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Method: horariosListAction ">//GEN-BEGIN:|63-action|0|63-preAction
    /**
     * Performs an action assigned to the selected list element in the
     * horariosList component.
     */
    public void horariosListAction() {//GEN-END:|63-action|0|63-preAction
        // enter pre-action user code here
        String __selectedString = getHorariosList().getString(getHorariosList().getSelectedIndex());//GEN-LINE:|63-action|1|63-postAction
        // enter post-action user code here
    }//GEN-BEGIN:|63-action|2|
//</editor-fold>//GEN-END:|63-action|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: imageItem ">//GEN-BEGIN:|70-getter|0|70-preInit
    /**
     * Returns an initialized instance of imageItem component.
     *
     * @return the initialized component instance
     */
    public ImageItem getImageItem() {
        if (imageItem == null) {//GEN-END:|70-getter|0|70-preInit
            // write pre-init user code here
            imageItem = new ImageItem("", getLogoImage(), ImageItem.LAYOUT_DEFAULT, "<Imagem perdida>");//GEN-LINE:|70-getter|1|70-postInit
            // write post-init user code here
        }//GEN-BEGIN:|70-getter|2|
        return imageItem;
    }
//</editor-fold>//GEN-END:|70-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: logoImage ">//GEN-BEGIN:|71-getter|0|71-preInit
    /**
     * Returns an initialized instance of logoImage component.
     *
     * @return the initialized component instance
     */
    public Image getLogoImage() {
        if (logoImage == null) {//GEN-END:|71-getter|0|71-preInit
            // write pre-init user code here
            try {//GEN-BEGIN:|71-getter|1|71-@java.io.IOException
                logoImage = Image.createImage("/logoGradeHoraria.png");
            } catch (java.io.IOException e) {//GEN-END:|71-getter|1|71-@java.io.IOException
                e.printStackTrace();
            }//GEN-LINE:|71-getter|2|71-postInit
            // write post-init user code here
        }//GEN-BEGIN:|71-getter|3|
        return logoImage;
    }
//</editor-fold>//GEN-END:|71-getter|3|

    /**
     * Returns a display instance.
     *
     * @return the display instance.
     */
    public Display getDisplay() {
        return Display.getDisplay(this);
    }

    /**
     * Exits MIDlet.
     */
    public void exitMIDlet() {
        switchDisplayable(null, null);
        destroyApp(true);
        notifyDestroyed();
    }

    /**
     * Called when MIDlet is started. Checks whether the MIDlet have been
     * already started and initialize/starts or resumes the MIDlet.
     */
    public void startApp() {
        if (midletPaused) {
            resumeMIDlet();
        } else {
            initialize();
            startMIDlet();
        }
        midletPaused = false;
    }

    /**
     * Called when MIDlet is paused.
     */
    public void pauseApp() {
        midletPaused = true;
    }

    /**
     * Called to signal the MIDlet to terminate.
     *
     * @param unconditional if true, then the MIDlet has to be unconditionally
     * terminated and all resources has to be released.
     */
    public void destroyApp(boolean unconditional) {
    }

    private String tratarTagsHtml(String textoOriginal) { // funcÃ£o que remove as tags html
        boolean substituir = false;
        StringBuffer buffer = new StringBuffer();
        char[] caracteres = textoOriginal.toCharArray();
        for (int i = 0; i < textoOriginal.length(); i++) {
            if (caracteres[i] == '<') {
                substituir = true;
            }

            if (caracteres[i] == '>') {
                caracteres[i] = ' ';
                substituir = false;
            }
            if (substituir == false) {
                buffer.append(caracteres[i]);
            }
        }
        return buffer.toString();
    }

    private Vector filtrarGrade(String tag) {

        String curso = "";
        String periodo = "";
        String diaSemana = "";

        if (cursoChoiceGroup.isSelected(0)) {
            curso = "ADS";
        } else if (cursoChoiceGroup.isSelected(1)) {
            curso = "COM.EX";
        } else if (cursoChoiceGroup.isSelected(2)) {
            curso = "COM.EX2";
        } else if (cursoChoiceGroup.isSelected(3)) {
            curso = "PQ";
        } else if (cursoChoiceGroup.isSelected(4)) {
            curso = "INF.GN";
        }

        if (periodoChoiceGroup.isSelected(0)) {
            periodo = "VESPERTINO";
        } else if (periodoChoiceGroup.isSelected(1)) {
            periodo = "NOTURNO";
        }

        if (diaChoiceGroup.isSelected(0)) {
            diaSemana = "2.ª";
        } else if (diaChoiceGroup.isSelected(1)) {
            diaSemana = "3.ª";
        } else if (diaChoiceGroup.isSelected(2)) {
            diaSemana = "4.ª";
        } else if (diaChoiceGroup.isSelected(3)) {
            diaSemana = "5.ª";
        } else if (diaChoiceGroup.isSelected(4)) {
            diaSemana = "6.ª";
        } else if (diaChoiceGroup.isSelected(5)) {
            diaSemana = "Sáb";
        }

        Vector horarios = new Vector();
        String[] arraySplit = new String[2];
        if (tag.indexOf(curso) != -1 && tag.indexOf(periodo) != -1 && tag.indexOf(diaSemana) != -1) {
            arraySplit = split(tag, "Horário:");
            horarios.addElement(arraySplit[1]);
            System.out.println(tag);
        }
        return horarios;
    }

    private String[] split(String original, String separator) {
        Vector nodes = new Vector();
        // Parse nodes into vector
        int index = original.indexOf(separator);
        while (index >= 0) {
            nodes.addElement(original.substring(0, index));
            original = original.substring(index + separator.length());
            index = original.indexOf(separator);
        }
        // Get the last node
        nodes.addElement(original);

        // Create split string array
        String[] result = new String[nodes.size()];
        if (nodes.size() > 0) {
            for (int loop = 0; loop < nodes.size(); loop++) {
                result[loop] = (String) nodes.elementAt(loop);
                System.out.println(result[loop]);
            }

        }
        return result;
    }
}
